package controller.admin;

import model.Goods;
import service.GoodsService;
import utils.FileUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "AdminGoodsDeleteServlet", value = "/admin/goods_delete")
public class AdminGoodsDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if ((id != null && !"".equals(id))) {
            GoodsService gs = new GoodsService();
            Goods goods = null;
            try {
                goods = gs.goods_detail(Integer.parseInt(id));
                if (goods != null) {
                    boolean flag = gs.deleteGoodsById(Integer.parseInt(id));
                    if (flag) {
                        String desPathStr = "D:" + File.separator + "DOME\\文档\\Practice\\Java Web\\蛋糕商场\\web\\";
                        //返回web应用程序文档根目录
                        String path = this.getServletContext().getRealPath("/");

                        FileUtils.deleteFile(path + goods.getCover());
                        FileUtils.deleteFile(desPathStr + goods.getCover());

                        FileUtils.deleteFile(path + goods.getImage1());
                        FileUtils.deleteFile(desPathStr + goods.getImage1());

                        FileUtils.deleteFile(path + goods.getImage2());
                        FileUtils.deleteFile(desPathStr + goods.getImage2());
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        response.sendRedirect(request.getHeader("Referer"));
    }
}
